#define  _CRT_SECURE_NO_WARNINGS 1
#include"SingleList.h"

SList* BuyListNode(DataType x)
{
	SList* newnode = (SList*)malloc(sizeof(SList));
	if (newnode == NULL)
	{
		printf("malloc is fail\n");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;

	return newnode;
}
void SListPrint(SList* head)
{
	assert(head);
	SList* cur = head;
	while (cur)
	{
		printf("%d", cur->data);
		cur = cur->next;
	}
	printf("\n");
}
void SListPushBack(SList** head, DataType x)
{
	assert(head);
	SList* newnode = BuyListNode(x);
	if ((*head) == NULL)
	{
		*head = newnode;
	}
	else
	{
		SList* tail = *head;
		while (tail->next)
		{
			tail = tail->next;
		}
		tail->next = newnode;
		newnode->next = NULL;
	}
}
void SListPushFront(SList** head, DataType x)
{
	assert(head);
	SList* newnode = BuyListNode(x);
	newnode->next = *head;
	*head = newnode;
}
void SListPopBack(SList** head)
{
	assert(head);
	if ((*head)->next == NULL)
	{
		free(*head);
		*head = NULL;
	}
	else
	{
		SList* tail = *head;
		SList* prev = NULL;
		while (tail->next)
		{
			prev = tail;
			tail = tail->next;
		}
		prev->next = NULL;
		free(tail);
		tail = NULL;
	}
}
void SListPopFront(SList** head)
{
	assert(head);
	SList* next = (*head)->next;
	free(*head);
	*head = next;
}
SList* SListFind(SList* head,DataType x)
{
	assert(head);
	SList* cur = head;
	while (cur)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}
void SListInsert(SList** head, SList* pos, DataType x)
{
	assert(head);
	assert(pos);
	if ((*head)->next == NULL)
	{
		SListPushFront(head, x);
	}
	else
	{
		SList* newnode = BuyListNode(x);
		SList* cur = *head;
		while (cur->next != pos)
		{
			cur = cur->next;
		}
		cur->next = newnode;
		newnode->next = pos;
	}
}
void SListErase(SList** head, SList* pos)
{
	assert(head);
	assert(pos);
	if ((*head)->next == NULL)
	{
		SListPopBack(head);
	}
	else
	{
		SList* cur = *head;
		while (cur->next != pos)
		{
			cur = cur->next;
		}
		cur->next = pos->next;
		free(pos);
		pos = NULL;
	}
}
void SListInsertAfter(SList* pos, DataType x)
{
	assert(pos);
	SList* newnode = BuyListNode(x);
	SList* next = pos->next;
	pos->next = newnode;
	newnode->next = next;
}
void SListEraseAfter(SList* pos)
{
	assert(pos);
	SList* del = pos->next;
	pos->next = del->next;
	free(del);
	del = NULL;
}